package com.diana.serviceImpl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition;
import com.diana.common.AliPayUtils;
import com.diana.common.IDUtil;
import com.diana.common.Utils;
import com.diana.entity.AlipayRecord;
import com.diana.entity.AlipayRefundRecord;
import com.diana.service.AlipayRecordService;
import com.diana.service.AlipayRefundRecordService;
import com.diana.service.AlipayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private AliPayUtils aliPayUtils;
    @Autowired
    private AlipayRecordService alipayRecordService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private AlipayRefundRecordService alipayRefundRecordService;

    private static final Logger log = LoggerFactory.getLogger(AlipayServiceImpl.class);

    @Override
    public String alipayNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("==========进入支付宝异步回调===========");
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        log.info("params is {}", params);
        boolean notifyCheck = aliPayUtils.notifyCheck(params);
        if(notifyCheck){
            String paramStr = request.getParameter("passback_params");
            String decode = null;
            try {
                decode = URLDecoder.decode(paramStr, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                log.error("支付宝回调转码异常{}:",e);
            }
            JSONObject param = Utils.toJson(decode);
            log.info("自定义参数passback_params:{}",param);

            String out_trade_no = request.getParameter("out_trade_no");
            String subject = request.getParameter("subject");
            String body = request.getParameter("body");
            String total_amount = request.getParameter("total_amount");
            AlipayRecord alipayRecord = new AlipayRecord();
            alipayRecord.setBody(body);
            alipayRecord.setOutTradeNo(out_trade_no);
            alipayRecord.setSubject(subject);
            alipayRecord.setAbleRefundAmount(new BigDecimal(total_amount));
            alipayRecord.setTotalAmount(new BigDecimal(total_amount));
            boolean insert = alipayRecordService.insert(alipayRecord);
            if(insert){
                log.info("支付记录插入数据成功");
            }else{
                log.error("支付记录插入数据失败");
            }
            return "success";
        }
        log.info("支付宝异步回调验签失败");
        return "fail";
    }

    @Override
    public void alipayReturn(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("==========进入支付宝同步回调===========");
        Map<String,String> param = new HashMap<String,String>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Iterator<String> iter = parameterMap.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) parameterMap.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            param.put(name, valueStr);
        }
        boolean notifyCheck = aliPayUtils.notifyCheck(param);
        if(notifyCheck){
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
            log.info("成功跳转:out_trade_no:" + out_trade_no + "<br/>total_amount:"+ total_amount);
            response.sendRedirect("http://49.232.55.114:9001/alipaySuccess.html");
            return;
        }else{
            log.info("验签失败");
        }
        response.sendRedirect("http://dianacloud.cn");
        return;
    }

    @Override
    public String doAlipayCheckParam(Map map) {
        String amount = Utils.toString(map.get("amount"));
        String message = Utils.toString(map.get("message"));
        if(StrUtil.isBlank(amount)){
            return Utils.message("0001","请输入金额",null);
        }
        if(!Utils.isNumDouble(amount)){
            return Utils.message("0001","请输入正确的金额格式",null);
        }
        if(StrUtil.isBlank(message)){
            return Utils.message("0001","请输入支付消息",null);
        }
        return Utils.message("0000","验证通过",map);
    }

    @Override
    public String doAlipay(String amount, String message) {
        String outTradeNo = IDUtil.getId()+"";
        String subject = "Diana沙箱支付测试";
        String s = aliPayUtils.tradePagePay(outTradeNo, amount, subject, message);
        return s;
    }

    @Override
    public String alipayRefund(Map map) {
        String outRequestNo = IDUtil.getId()+"";
        String outTradeNo = Utils.toString(map.get("outTradeNo"));
        String refundAmount = Utils.toString(map.get("refundAmount"));
        String refundReason = Utils.toString(map.get("refundReason"));
        String managerId = request.getHeader("managerId");
        if(Utils.isNullOrEmpty(outTradeNo)||Utils.isNullOrEmpty(refundAmount)){
            return Utils.message("0000","参数不能为空",null);
        }
        if(!Utils.isNumDouble(refundAmount)){
            return Utils.message("0001","请输入正确的金额格式",null);
        }
        /*AlipayRecord alipayRecord = alipayRecordService.selectOne(Condition.create().eq("outTradeNo", outTradeNo));

        BigDecimal refundAmountB = new BigDecimal(refundAmount);
        if(alipayRecord.getAbleRefundAmount().compareTo(refundAmountB)==-1){
            return Utils.message("0001","该订单可退款余额不足",null);
        }*/

        String result = aliPayUtils.refund(outRequestNo, outTradeNo, refundAmount, refundReason, managerId);
        JSONObject jsonObject = Utils.toJson(result);
        String code = jsonObject.getString("code");
        if("0000".equals(code)){
            AlipayRefundRecord alipayRefundRecord = new AlipayRefundRecord();
            alipayRefundRecord.setOutRequestNo(outRequestNo);
            alipayRefundRecord.setOutTradeNo(outTradeNo);
            alipayRefundRecord.setOperatorId(managerId);
            alipayRefundRecord.setRefundAmount(new BigDecimal(refundAmount));
            alipayRefundRecord.setRefundReason(refundReason);
            boolean insert = alipayRefundRecordService.insert(alipayRefundRecord);
            if(insert){
                return Utils.message("0000","退款成功",null);
            }
            return Utils.message("0000","退款成功,记录数据失败",null);
        }
        return result;
    }
}
